package me.zhengjie.modules.equipment.service.impl;

import me.zhengjie.modules.equipment.domain.TWarehouse;
import me.zhengjie.utils.ValidationUtil;
import me.zhengjie.modules.equipment.repository.TWarehouseRepository;
import me.zhengjie.modules.equipment.service.TWarehouseService;
import me.zhengjie.modules.equipment.service.dto.TWarehouseDTO;
import me.zhengjie.modules.equipment.service.dto.TWarehouseQueryCriteria;
import me.zhengjie.modules.equipment.service.mapper.TWarehouseMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import java.util.Optional;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import me.zhengjie.utils.PageUtil;
import me.zhengjie.utils.QueryHelp;

/**
* @author sw
* @date 2019-06-30
*/
@Service
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class)
public class TWarehouseServiceImpl implements TWarehouseService {

    @Autowired
    private TWarehouseRepository tWarehouseRepository;

    @Autowired
    private TWarehouseMapper tWarehouseMapper;

    @Override
    public Object queryAll(TWarehouseQueryCriteria criteria, Pageable pageable){
        Page<TWarehouse> page = tWarehouseRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder),pageable);
        return PageUtil.toPage(page.map(tWarehouseMapper::toDto));
    }

    @Override
    public Object queryAll(TWarehouseQueryCriteria criteria){
        return tWarehouseMapper.toDto(tWarehouseRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder)));
    }

    @Override
    public TWarehouseDTO findById(Integer id) {
        Optional<TWarehouse> tWarehouse = tWarehouseRepository.findById(id);
        ValidationUtil.isNull(tWarehouse,"TWarehouse","id",id);
        return tWarehouseMapper.toDto(tWarehouse.get());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public TWarehouseDTO create(TWarehouse resources) {
        return tWarehouseMapper.toDto(tWarehouseRepository.save(resources));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(TWarehouse resources) {
        Optional<TWarehouse> optionalTWarehouse = tWarehouseRepository.findById(resources.getId());
        ValidationUtil.isNull( optionalTWarehouse,"TWarehouse","id",resources.getId());

        TWarehouse tWarehouse = optionalTWarehouse.get();
        // 此处需自己修改
        resources.setId(tWarehouse.getId());
        tWarehouseRepository.save(resources);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delete(Integer id) {
        tWarehouseRepository.deleteById(id);
    }
}